package com.glacier.demo.handle;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.glacier.framework.component.dto.response.Response;
import com.glacier.framework.component.dto.response.StatusCode;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * date 2024-01-30 15:16
 *
 * @author glacier
 * @version 1.0
 */
@Slf4j
public class GlobalBlockExceptionHandler implements BlockExceptionHandler {

    private final ObjectMapper objectMapper;

    public GlobalBlockExceptionHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }


    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        log.info("拦截到异常：{}", e.getMessage());
        Response<String> response = null;

        if (e instanceof FlowException) {
            response = Response.error(StatusCode.SERVICE_THROTTLING);
        } else if (e instanceof DegradeException) {
            response = Response.error(StatusCode.SERVICE_DEGRADATION);
        } else if (e instanceof ParamFlowException) {
            response = Response.error(StatusCode.THE_HOTSPOT_PARAMETER_THROTTLES);
        } else if (e instanceof SystemBlockException) {
            response = Response.error(StatusCode.SYSTEM_PROTECTION);
        } else if (e instanceof AuthorityException) {
            response = Response.error(StatusCode.AUTHORIZATION_RULE_IS_NOT_PASSED);
        }
        // http状态码
        httpServletResponse.setStatus(500);
        httpServletResponse.setCharacterEncoding(StandardCharsets.UTF_8.name());
        httpServletResponse.setHeader("Content-Type", "application/json;charset=utf-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        // spring mvc自带的json操作工具，叫jackson
        objectMapper.writeValue(httpServletResponse.getWriter(), response);

    }
}
